<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '发帖',
    navigationBarBackgroundColor: '#f8f8f8',
    navigationBarTextStyle: 'black'
  },
}
</route>

<template>
  <view class="create-post-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">发布动态</text>
      <text class="page-subtitle">分享你的阅读心得和想法</text>
    </view>

    <!-- 发帖表单 -->
    <view class="post-form">
      <!-- 正文输入区 -->
      <view class="content-section">
        <textarea
          v-model="postContent"
          class="content-input"
          placeholder="分享你的想法..."
          :maxlength="500"
          auto-height
          :show-confirm-bar="false"
          @input="onContentInput"
        />
        <view class="char-count">
          <text :class="{ 'over-limit': postContent.length > 500 }">
            {{ postContent.length }}/500
          </text>
        </view>
      </view>

      <!-- 图片上传区 -->
      <view class="image-section">
        <view class="image-grid">
          <view
            v-for="(image, index) in uploadedImages"
            :key="index"
            class="image-item"
          >
            <image :src="image.url" mode="aspectFill" class="uploaded-image" />
            <view class="image-delete" @click="removeImage(index)">
              <wd-icon name="delete" size="10px" color="#fff"></wd-icon>
            </view>
          </view>
          
          <!-- 添加图片按钮 -->
          <view
            v-if="uploadedImages.length < 3"
            class="add-image-btn"
            @click="chooseImage"
          >
            <uni-icons type="camera" size="24" color="#42bbff"></uni-icons>
            <text class="add-text">添加图片</text>
          </view>
        </view>
        
        <view class="image-tip">
          <text class="tip-text">最多上传3张图片，支持JPEG/PNG格式，单张不超过5MB</text>
        </view>
      </view>

      <!-- 附件上传区 -->
      <view class="attachment-section">
        <view class="section-title">
          <text class="title-text">附件</text>
          <text class="title-desc">（暂未开放）</text>
        </view>
        <button class="attachment-btn" @click="showAttachmentTip" disabled>
          <uni-icons type="paperclip" size="20" color="#94a3b8"></uni-icons>
          <text class="btn-text">添加附件</text>
        </button>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-buttons">
        <button class="draft-btn" @click="saveDraft">
          <uni-icons type="folder-add" size="16" color="#94a3b8"></uni-icons>
          <text class="btn-text">保存草稿</text>
        </button>

        <!-- <button class="clear-draft-btn" @click="clearDraft" v-if="hasDraftContent">
          <uni-icons type="trash" size="16" color="#f56565"></uni-icons>
          <text class="btn-text">清除草稿</text>
        </button> -->

        <button
          class="publish-btn"
          :class="{ 'disabled': !canPublish }"
          :disabled="!canPublish"
          @click="publishPost"
        >
          <text class="btn-text">发布</text>
        </button>
      </view>
    </view>

    <!-- 加载遮罩 -->
    <view v-if="isUploading" class="loading-overlay">
      <view class="loading-content">
        <uni-icons type="spinner-cycle" size="24" color="#42bbff"></uni-icons>
        <text class="loading-text">{{ uploadingText }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { createPost, checkSensitiveWords, checkPostLimit, PostType, type PostCreateReqVO, saveDraft as saveDraftApi, getDraft as getDraftApi, physicalDeleteDraft as physicalDeleteDraftApi } from '@/api/community'

// 表单数据
const postContent = ref('')
const uploadedImages = ref<{ url: string; file?: File }[]>([])

// 状态管理
const isUploading = ref(false)
const uploadingText = ref('上传中...')
const isPublishSuccess = ref(false) // 发布成功标志
let saveDraftTimer: number | null = null

// 计算属性
const canPublish = computed(() => {
  return (postContent.value.trim().length > 0 || uploadedImages.value.length > 0) &&
         postContent.value.length <= 500
})

const hasDraftContent = computed(() => {
  return postContent.value.trim().length > 0 || uploadedImages.value.length > 0
})

// 防抖保存草稿
function debouncedSaveDraft() {
  // 如果已经发布成功，不再保存草稿
  if (isPublishSuccess.value) {
    return
  }

  if (saveDraftTimer) {
    clearTimeout(saveDraftTimer)
  }
  saveDraftTimer = setTimeout(() => {
    saveDraftToServer()
  }, 2000) // 2秒后保存
}

// 物理删除草稿（带重试机制）
async function physicalDeleteDraftWithRetry(maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await physicalDeleteDraftApi()
      if (response.code === 0) {
        console.log('服务器草稿物理删除成功')
        return
      } else {
        throw new Error(response.msg || '物理删除草稿失败')
      }
    } catch (error) {
      console.warn(`物理删除服务器草稿失败 (尝试 ${i + 1}/${maxRetries}):`, error)

      if (i === maxRetries - 1) {
        // 最后一次尝试失败，记录错误但不阻止发布流程
        console.error('物理删除服务器草稿最终失败，但帖子已发布成功')
        uni.showToast({
          title: '帖子发布成功，但草稿清理失败',
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }
}

// 清除草稿
async function clearDraft() {
  uni.showModal({
    title: '确认清除',
    content: '确定要清除当前草稿吗？此操作不可恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 显示清除中提示
          uni.showLoading({
            title: '清除中...'
          })

          // 物理删除服务器草稿
          await physicalDeleteDraftWithRetry()

          // 清除本地草稿
          uni.removeStorageSync('post_draft')

          // 清除页面内容
          postContent.value = ''
          uploadedImages.value = []

          // 设置标志，防止页面卸载时再次保存草稿
          isPublishSuccess.value = true

          // 清除防抖定时器
          if (saveDraftTimer) {
            clearTimeout(saveDraftTimer)
            saveDraftTimer = null
          }

          uni.showToast({
            title: '草稿已清除',
            icon: 'success'
          })
        } catch (error) {
          console.error('清除草稿失败:', error)
          uni.showToast({
            title: '清除草稿失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 正文输入处理
function onContentInput(e: any) {
  postContent.value = e.detail.value
  // 自动保存草稿到服务器（防抖处理）
  debouncedSaveDraft()
}

// 选择图片
function chooseImage() {
  uni.chooseImage({
    count: 3 - uploadedImages.value.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = Array.isArray(res.tempFilePaths) ? res.tempFilePaths : [res.tempFilePaths]
      tempFilePaths.forEach(async (filePath) => {
        // 检查文件大小
        uni.getFileInfo({
          filePath,
          success: (fileInfo) => {
            if (fileInfo.size > 5 * 1024 * 1024) { // 5MB
              uni.showToast({
                title: '图片大小不能超过5MB',
                icon: 'none'
              })
              return
            }
            
            // 添加到上传列表
            uploadedImages.value.push({
              url: filePath
            })

            // 自动保存草稿
            debouncedSaveDraft()
          }
        })
      })
    }
  })
}

// 移除图片
function removeImage(index: number) {
  uploadedImages.value.splice(index, 1)
  debouncedSaveDraft()
}

// 保存草稿到服务器
async function saveDraftToServer() {
  try {
    // 如果已经发布成功，不再保存草稿
    if (isPublishSuccess.value) {
      return
    }

    // 只有当有内容或图片时才保存草稿
    if (!postContent.value.trim() && uploadedImages.value.length === 0) {
      return
    }

    // 准备图片URL列表
    const imageUrls: string[] = []
    for (const image of uploadedImages.value) {
      if (image.url.startsWith('http')) {
        // 已上传的图片URL
        imageUrls.push(image.url)
      } else {
        // 本地图片需要先上传
        try {
          const uploadedUrl = await uploadImageFile(image.url)
          imageUrls.push(uploadedUrl)
        } catch (error) {
          console.warn('草稿图片上传失败:', error)
          // 图片上传失败时跳过该图片，不影响草稿保存
        }
      }
    }

    // 调用API保存草稿
    await saveDraftApi(postContent.value.trim(), imageUrls)
    console.log('草稿保存成功')
  } catch (error) {
    console.error('保存草稿失败:', error)
    // 保存失败时回退到本地存储
    saveDraftToLocal()
  }
}

// 保存草稿到本地（作为备用方案）
function saveDraftToLocal() {
  const draft = {
    content: postContent.value,
    images: uploadedImages.value,
    timestamp: Date.now()
  }
  uni.setStorageSync('post_draft', draft)
}

// 从服务器读取草稿
async function loadDraftFromServer() {
  try {
    const response = await getDraftApi()
    if (response.code === 0 && response.data) {
      const draftData = response.data as any
      postContent.value = draftData.content || ''

      // 处理图片数据
      if (draftData.images && Array.isArray(draftData.images)) {
        uploadedImages.value = draftData.images.map((url: string) => ({ url }))
      }

      console.log('从服务器加载草稿成功')
    }
  } catch (error) {
    console.warn('从服务器读取草稿失败，尝试读取本地草稿:', error)
    // 服务器读取失败时，尝试读取本地草稿
    loadDraftFromLocal()
  }
}

// 读取本地草稿（作为备用方案）
function loadDraftFromLocal() {
  try {
    const draft = uni.getStorageSync('post_draft')
    if (draft && draft.content) {
      postContent.value = draft.content
      uploadedImages.value = draft.images || []
    }
  } catch (error) {
    console.error('读取草稿失败:', error)
  }
}

// 保存草稿
async function saveDraft() {
  // 如果已经发布成功，提示用户
  if (isPublishSuccess.value) {
    uni.showToast({
      title: '内容已发布，无需保存草稿',
      icon: 'none'
    })
    return
  }

  if (!postContent.value.trim() && uploadedImages.value.length === 0) {
    uni.showToast({
      title: '请输入内容或添加图片',
      icon: 'none'
    })
    return
  }

  try {
    // 显示保存中提示
    uni.showLoading({
      title: '保存中...'
    })

    // 准备图片URL列表
    const imageUrls: string[] = []
    for (const image of uploadedImages.value) {
      if (image.url.startsWith('http')) {
        // 已上传的图片URL
        imageUrls.push(image.url)
      } else {
        // 本地图片需要先上传
        try {
          const uploadedUrl = await uploadImageFile(image.url)
          imageUrls.push(uploadedUrl)
        } catch (error) {
          console.warn('草稿图片上传失败:', error)
          // 图片上传失败时跳过该图片，不影响草稿保存
        }
      }
    }

    // 调用API保存草稿
    const response = await saveDraftApi(postContent.value.trim(), imageUrls)

    if (response.code === 0) {
      uni.showToast({
        title: '草稿已保存',
        icon: 'success'
      })
    } else {
      throw new Error(response.msg || '保存草稿失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)

    // 保存失败时回退到本地存储
    saveDraftToLocal()

    uni.showToast({
      title: '草稿已保存到本地',
      icon: 'success'
    })
  } finally {
    uni.hideLoading()
  }
}

// 显示附件功能提示
function showAttachmentTip() {
  uni.showToast({
    title: '附件功能暂未开放',
    icon: 'none'
  })
}

// 上传单个图片文件
async function uploadImageFile(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: '/reading/community/upload/image',
      filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${uni.getStorageSync('token')}`,
        'platform': 'app'
      },
      success: (res) => {
        try {
          console.log('图片上传响应:', res)
          const response = JSON.parse(res.data)
          if (response.code === 0 && response.data) {
            resolve(response.data)
          } else {
            reject(new Error(response.msg || '图片上传失败'))
          }
        } catch (error) {
          console.error('图片上传响应解析失败:', error, res)
          reject(new Error('图片上传响应解析失败'))
        }
      },
      fail: (error) => {
        reject(new Error(`图片上传失败: ${error.errMsg}`))
      }
    })
  })
}

// 发布帖子
async function publishPost() {
  // 前端验证
  const trimmedContent = postContent.value.trim()
  console.log('发布帖子 - 内容长度:', trimmedContent.length, '图片数量:', uploadedImages.value.length)

  if (!canPublish.value) {
    uni.showToast({
      title: '请输入内容或添加图片',
      icon: 'none'
    })
    return
  }

  // 额外验证：确保有内容或图片
  if (trimmedContent.length === 0 && uploadedImages.value.length === 0) {
    uni.showToast({
      title: '请输入内容或添加图片',
      icon: 'none'
    })
    return
  }

  // 内容长度验证
  if (trimmedContent.length > 500) {
    uni.showToast({
      title: '内容不能超过500字',
      icon: 'none'
    })
    return
  }

  try {
    isUploading.value = true
    uploadingText.value = '检查发帖权限...'

    // 1. 检查发帖频控
    const limitResponse = await checkPostLimit()
    console.log('频控检查响应:', limitResponse)

    if (limitResponse.code === 0 && limitResponse.data) {
      const limitData = limitResponse.data as any
      console.log('频控数据:', limitData)

      if (!limitData.canOperate) {
        // 如果不能发帖，使用后端返回的消息或生成合适的消息
        const message = limitData.message ||
          `今日发帖次数已达上限（${limitData.remainingCount || 0}次剩余），请明天再试`
        throw new Error(message)
      } else {
        console.log(`发帖检查通过，剩余次数：${limitData.remainingCount}`)
      }
    } else {
      console.warn('频控检查失败:', limitResponse.msg)
    }

    // 2. 敏感词检测
    if (postContent.value.trim()) {
      uploadingText.value = '内容审核中...'
      const sensitiveResponse = await checkSensitiveWords(postContent.value.trim())

      if (sensitiveResponse.code === 0 && sensitiveResponse.data) {
        const sensitiveData = sensitiveResponse.data as any
        if (sensitiveData.hasSensitive) {
          throw new Error(`内容包含敏感词：${sensitiveData.sensitiveWords.join('、')}，请修改后重试`)
        }
      }
    }

    // 3. 上传图片
    const imageUrls: string[] = []
    if (uploadedImages.value.length > 0) {
      uploadingText.value = '上传图片中...'

      for (let i = 0; i < uploadedImages.value.length; i++) {
        const image = uploadedImages.value[i]
        try {
          uploadingText.value = `上传图片中... (${i + 1}/${uploadedImages.value.length})`

          // 使用uni.uploadFile上传到我们的API接口
          const uploadResult = await uploadImageFile(image.url)
          imageUrls.push(uploadResult)
          console.log(`第${i + 1}张图片上传成功:`, uploadResult)
        } catch (error) {
          console.error('图片上传失败:', error)
          throw new Error(`第${i + 1}张图片上传失败: ${error instanceof Error ? error.message : '未知错误'}`)
        }
      }
    }

    // 4. 创建帖子数据
    const finalContent = postContent.value.trim()
    const postData: PostCreateReqVO = {
      type: PostType.NORMAL,
      content: finalContent || ' ', // 如果内容为空，传递一个空格字符，避免后端验证问题
      images: imageUrls
    }

    // 最终验证
    console.log('最终发布数据:', {
      content: finalContent,
      contentLength: finalContent.length,
      images: imageUrls,
      imageCount: imageUrls.length
    })

    // 前端已经验证过了，这里不需要再次验证
    // if (finalContent.length === 0 && imageUrls.length === 0) {
    //   throw new Error('帖子内容和图片不能同时为空')
    // }

    uploadingText.value = '发布中...'
    console.log('发送到后端的数据:', JSON.stringify(postData, null, 2))
    const response = await createPost(postData)

    if (response.code === 0) {
      // 设置发布成功标志，防止页面卸载时再次保存草稿
      isPublishSuccess.value = true

      // 发布成功后物理删除服务器草稿
      await physicalDeleteDraftWithRetry()

      // 清除本地草稿
      uni.removeStorageSync('post_draft')

      // 清空页面内容，防止页面卸载时检测到有内容而保存草稿
      postContent.value = ''
      uploadedImages.value = []

      uni.showToast({
        title: '发布成功',
        icon: 'success'
      })

      // 跳转到帖子详情页
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages-sub/community/post-detail/index?id=${response.data}`
        })
      }, 1500)
    } else {
      throw new Error(response.msg || '发布失败')
    }
  } catch (error) {
    console.error('发布帖子失败:', error)
    uni.showToast({
      title: error instanceof Error ? error.message : '发布失败',
      icon: 'none',
      duration: 3000
    })

    // 发布失败时自动保存草稿
    saveDraftToLocal()
  } finally {
    isUploading.value = false
  }
}

onLoad(() => {
  // 加载服务器草稿
  loadDraftFromServer()
})

onUnload(() => {
  // 页面卸载时自动保存草稿（但如果是发布成功后跳转则不保存）
  if (!isPublishSuccess.value && (postContent.value.trim() || uploadedImages.value.length > 0)) {
    // 清除防抖定时器
    if (saveDraftTimer) {
      clearTimeout(saveDraftTimer)
    }
    // 立即保存草稿到服务器
    saveDraftToServer()
    // 同时保存到本地作为备份
    saveDraftToLocal()
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.create-post-container {
  min-height: 100vh;
  background: $bg-gradient;
  padding: $container-padding;
  padding-bottom: 100px; // 为底部操作栏留空间
}

.page-header {
  text-align: center;
  margin-bottom: 24px;
  padding: 0;

  .page-title {
    display: block;
    font-size: 24px;
    font-weight: 700;
    color: $dark-gray;
    margin-bottom: 8px;
    background: linear-gradient(135deg, $primary-blue 0%, $purple 100%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .page-subtitle {
    display: block;
    font-size: 14px;
    color: $medium-gray;
    font-weight: 400;
    opacity: 0.8;
  }
}

.post-form {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: $glass-blur;
  border-radius: $border-radius-xl;
  padding: 24px;
  box-shadow: $shadow-lg;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.content-section {
  margin-bottom: 28px;

  .content-input {
    width: 100%;
    min-height: 140px;
    // padding: 18px;
    background: rgba(248, 250, 252, 0.8);
    border: 2px solid transparent;
    // border-radius: $border-radius-xl;
    font-size: 16px;
    line-height: 1.6;
    color: $dark-gray;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(66, 187, 255, 0.1);

    &:focus {
      background: rgba(255, 255, 255, 0.95);
      border-color: rgba(66, 187, 255, 0.3);
      box-shadow: 0 4px 16px rgba(66, 187, 255, 0.2);
      transform: translateY(-1px);
    }

    &::placeholder {
      color: $medium-gray;
      font-weight: 400;
    }
  }

  .char-count {
    text-align: right;
    margin-top: 12px;

    text {
      font-size: 13px;
      color: $medium-gray;
      font-weight: 500;

      &.over-limit {
        color: $coral;
        font-weight: 600;
      }
    }
  }
}

.image-section {
  margin-bottom: 28px;

  .image-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    margin-bottom: 16px;
  }

  .image-item {
    position: relative;
    width: 88px;
    height: 88px;
    border-radius: $border-radius-lg;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
    }

    .uploaded-image {
      width: 100%;
      height: 100%;
    }

    .image-delete {
      position: absolute;
      top: 2px;
      right: 2px;
      width: 24px;
      height: 24px;
      background: linear-gradient(135deg, $coral 0%, #ff6b6b 100%);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
      transition: all 0.2s ease;

      &:active {
        transform: scale(0.9);
      }
    }
  }

  .add-image-btn {
    width: 88px;
    height: 88px;
    border: 2px dashed rgba(66, 187, 255, 0.4);
    border-radius: $border-radius-lg;
    background: rgba(66, 187, 255, 0.05);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      background: rgba(66, 187, 255, 0.1);
      border-color: rgba(66, 187, 255, 0.6);
    }

    .add-text {
      font-size: 11px;
      color: $primary-blue;
      font-weight: 500;
    }
  }

  .image-tip {
    background: rgba(66, 187, 255, 0.08);
    padding: 12px 16px;
    border-radius: $border-radius-lg;
    border-left: 3px solid $primary-blue;

    .tip-text {
      font-size: 13px;
      color: $dark-gray;
      line-height: 1.5;
      font-weight: 400;
    }
  }
}

.attachment-section {
  margin-bottom: 28px;

  .section-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 16px;

    .title-text {
      font-size: 17px;
      font-weight: 600;
      color: $dark-gray;
    }

    .title-desc {
      font-size: 12px;
      color: $medium-gray;
      background: rgba(148, 163, 184, 0.1);
      padding: 2px 8px;
      border-radius: 10px;
      font-weight: 500;
    }
  }

  .attachment-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    width: 100%;
    padding: 18px;
    background: rgba(148, 163, 184, 0.08);
    border: 2px dashed rgba(148, 163, 184, 0.3);
    border-radius: $border-radius-xl;
    transition: all 0.3s ease;

    .btn-text {
      font-size: 15px;
      color: $medium-gray;
      font-weight: 500;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    &:not(:disabled):active {
      transform: scale(0.98);
      background: rgba(148, 163, 184, 0.12);
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: $glass-blur;
  border-top: 1px solid rgba(66, 187, 255, 0.1);
  padding: 18px 24px;
  padding-bottom: calc(18px + env(safe-area-inset-bottom));
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);

  .action-buttons {
    display: flex;
    gap: 16px;
    align-items: center;
  }

  .draft-btn {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    background: rgba(148, 163, 184, 0.1);
    border: 1px solid rgba(148, 163, 184, 0.2);
    border-radius: 24px;
    font-size: 14px;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      background: rgba(148, 163, 184, 0.15);
    }

    .btn-text {
      color: $dark-gray;
      font-weight: 500;
    }
  }

  .clear-draft-btn {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: rgba(245, 101, 101, 0.1);
    border: 1px solid rgba(245, 101, 101, 0.2);
    border-radius: 24px;
    font-size: 14px;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      background: rgba(245, 101, 101, 0.15);
    }

    .btn-text {
      color: #f56565;
      font-weight: 500;
    }
  }

  .publish-btn {
    flex: 1;
    padding: 7px 24px;
    background: linear-gradient(135deg, $primary-blue 0%, $sky-blue 100%);
    border: none;
    border-radius: 24px;
    box-shadow: 0 4px 16px rgba(66, 187, 255, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: translateY(1px);
      box-shadow: 0 2px 8px rgba(66, 187, 255, 0.4);
    }

    .btn-text {
      color: $white;
      font-size: 16px;
      font-weight: 600;
    }

    &.disabled {
      background: linear-gradient(135deg, $medium-gray 0%, $light-gray 100%);
      box-shadow: none;

      .btn-text {
        color: rgba(255, 255, 255, 0.7);
      }
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: $glass-blur-sm;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: $z-index-modal;
  animation: fadeIn 0.3s ease;

  .loading-content {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: $glass-blur;
    padding: 32px 28px;
    border-radius: $border-radius-xl;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    min-width: 160px;

    .loading-text {
      font-size: 15px;
      color: $dark-gray;
      font-weight: 500;
      text-align: center;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
